package de.alt.rest.handler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import de.alt.rest.constants.Constants;
import de.alt.rest.constants.DBConstants;
import de.alt.rest.service.RestService;
import de.alt.rest.util.GeneralSuperUtil;

/**
 * The Class CronHandler.
 */
public class CronHandler {

	/** The Constant log. */
	private static final Logger log = Logger.getLogger(RestService.class.getName());

	/**
	 * Do cron.
	 */
	public String doCron() {
		Entity homeAddress = new GeneralSuperUtil().getById(DBConstants.TABLE_ADDRESS, "home");

		String address = (String) homeAddress.getProperty(DBConstants.TABLE_ADDRESS_ADDR);

		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		String result = "";
		try {
			url = new URL("http://" + address);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while ((line = rd.readLine()) != null) {
				result += line;
			}
			rd.close();
		} catch (Exception e) {
			log.warning(e.getMessage());
			return Constants.STAUS_NOK;
		}

		Entity cronInfo = new Entity(DBConstants.TABLE_CRONINFO);
		cronInfo.setProperty(DBConstants.TABLE_CRONINFO_RESP, result);

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		datastore.put(cronInfo);
		return Constants.STAUS_OK;
	}

}
